# coding: utf-8
"""API for setup/usage of Canoe COM Client interface.
"""
# --------------------------------------------------------------------------
# Standard library imports
from mylog import *

import os
import sys
import subprocess
import time
import msvcrt
from win32com.client import *
from win32com.client.connect import *


# Vector Canoe Class
class CANoe:
    def __init__(self):
        self.application = None
        self.application = DispatchEx("CANoe.Application")
        self.ver = self.application.Version
        logger.info('Loaded CANoe version:{}.{}.{}'.format(self.ver.major, self.ver.minor, self.ver.Build)) #, sep,''
        self.Measurement = self.application.Measurement.Running

    def open_cfg(self, cfgname):
        # open CANoe simulation
        logger.info('准备打开canoe')
        if (self.application != None):
            # check for valid file and it is *.cfg file
            if os.path.isfile(cfgname) and (os.path.splitext(cfgname)[1] == ".cfg"):
                self.application.Open(cfgname)
                logger.info("opening...{}".format(cfgname))
            else:
                raise RuntimeError("Can't find CANoe cfg file")
        else:
            raise RuntimeError("CANoe Application is missing,unable to open simulation")

    def close_cfg(self):
        logger.info('准备关闭canoe')
        if (self.application != None):
            # self.stop_Measurement()
            self.application.Quit()
            self.application = None


    def start_Measurement(self):
        logger.info('准备执行工程')
        retry = 0
        retry_counter = 5
        # try to establish measurement within 5s timeout
        while not self.application.Measurement.Running and (retry < retry_counter):
            self.application.Measurement.Start()
            time.sleep(1)
            retry += 1
        if (retry == retry_counter):
            raise RuntimeWarning("CANoe start measuremet failed, Please Check Connection!")


    def stop_Measurement(self):
        if self.application.Measurement.Running:
            self.application.Measurement.Stop()
        else:
            pass


    def get_SigVal(self, channel_num, msg_name, sig_name, bus_type="CAN"):
        """
        在CAN模拟总线上获取原始CAN信号的值
        channel_num - 整数值, 表示从哪个通道读取信号, 通常从1开始, 用CANoe检查是否可以设置通道
        msg_name - 字符串值, 指示信号所属的消息名称。检查DBC设置
        sig_name - 要读取的信号的字符串值
        bus_type - String value of the bus type - e.g. "CAN", "LIN" and etc
        return 浮点数, CAN信号值。即使信号是整数类型, 我们仍然将返回浮点值。
        """
        if (self.application != None):
            result = self.application.GetBus(bus_type).GetSignal(channel_num, msg_name, sig_name)
            return result.Value
        else:
            raise RuntimeError("CANoe没有打开, 无法获取信号")


    def set_SigVal(self, channel_num, msg_name, sig_name, bus_type,setValue):
        if (self.application != None):
            result = self.application.GetBus(bus_type).GetSignal(channel_num, msg_name, sig_name)
            result.Value = setValue
        else:
            raise RuntimeError("CANoe没有打开, 无法获取信号")


    def DoEvents(self):
        pythoncom.PumpWaitingMessages()
        time.sleep(1)


app = CANoe() #定义CANoe为app
app.open_cfg(r"E:/Luxshare/CANoeProject/RLWLC BT Project ModuleV1.2/chehejia_bootloader_v1.2.cfg")   #导入某个CANoe congif
time.sleep(5)

app.start_Measurement()

while not msvcrt.kbhit():
    # app.set_SigVal(channel_num=1, msg_name="EngineState", sig_name="EngineSpeed", bus_type="CAN", setValue=1)
    EngineSpeed = app.get_SigVal(channel_num = 2, msg_name = "RLWLC_SWID", sig_name = "RLWLC_VerNum", bus_type = "CAN")
    print(EngineSpeed)
    app.DoEvents()